

import time
import numpy as np
import cv2
import keti4_config as config
import op_route
# import keti4_config as config
# from protocol import BinaryProtocol as bp

class aidStarInfo:
    def __init__(self, id=1, name="aid start 1", host="127.0.0.1", port="8888"):
        self.id = id
        self.name = name
        self.host = host
        self.port = port
aid_star_info  = aidStarInfo()


# 计算辅星接收来自计算主星的数据，计算完成后，把结果返回给计算主星
# def run():
#     # 1. 接收计算主星发送的数据
#     data = receive_data()
#     # 2. 计算
#     result = calculate(data)
# 
#     save_binary_to_file(result, filename="result.png")
# 
#     # save_binary_to_file(data, file_path):
# 
#     # 3. 发送计算结果给计算主星
#     send_result_to_main_star(result)

def receive_data(recv_port = 8800):
    # 接收数据
    router = op_route.RouterClient(host='localhost', port=recv_port)
    # data = router.receive_packet()
    data_type, src_id, dst_id, data_length, data = router.receive_packet()

    return data_type, src_id, dst_id, data_length, data 

def calculate(data):

    for i in range(100):
        time.sleep(1)
        print(f"[aid star processing ...] ... {i}/100")

    # 计算
    return data


def save_binary_to_file(data, file_path):
    """
    将二进制数据保存为文件
    """
    try:
        with open(file_path, 'wb') as f:  # 二进制写入模式
            f.write(data)
        print(f"[Receiver] 数据已保存到文件 {file_path}")
    except Exception as e:
        print(f"[Receiver] 文件保存失败: {e}")


def send_result_to_main_star(result, target_node=0x01, send_port = 8800):
    # 发送计算结果给计算主星
    router = op_route.RouterClient(host='localhost', port=send_port)
    router.connect()

    # encoded_result = bp.encode("result", result)
    # 标签，用于区分不同的数据（暂定）

    # label = aid_star_info.name+aid_star_info.id 
    # encoded_result = bp.encode(label=label, data=result)

    # router.send_packet(data_type=op_route.DATA_TYPE_SEND, dst_id=target_node, len=len(result), data=result)

    router.send_packet(data_type=op_route.DATA_TYPE_SEND, dst_id=target_node, len=len(result), data=result)
    # print("Sent result:", result)



if __name__ == "__main__":

    # 获取命令行参数
    # script_name = sys.argv[0]  # 脚本名
    # arguments = sys.argv[1:]   # 除脚本名外的参数列表

    # data = read_data(sys.argv[1])   # 除脚本名外的参数列表
    # target_node = sys.argv[2]  # 脚本名

    # recv_port = 8088
    # snd_port = 8088
    # target_node = 0x02  # 目标节点名称

    # 1. 接收计算主星发送的数据
    data_type, src_id, dst_id, data_length, data  = receive_data(config.recv_port)

    # 2. 计算
    result = calculate(data)

    save_binary_to_file(result, filename="result.png")

    target_node = src_id
    # 3. 发送计算结果给计算主星
    send_result_to_main_star(result, 
                             target_node=target_node, 
                             send_port=config.send_port)

    while(True):
        time.sleep(1)





